package cn.stylefeng.guns.sys.modular.system.service;

import cn.stylefeng.guns.sys.modular.system.entity.BtyInventory;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyInventoryMapper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class BtyInventoryService extends ServiceImpl<BtyInventoryMapper, BtyInventory> {
    private Logger logger = LoggerFactory.getLogger(BtyInventoryService.class);
    @Autowired
    private BtyInventoryMapper btyInventoryMapper;

    private RestTemplate restTemplate = new RestTemplate();


    public int insertData(BtyInventory btyInventory) {
        return this.btyInventoryMapper.insertData(btyInventory);
    }

    public List<BtyInventory> selectMD(String dm) {
        return this.btyInventoryMapper.selectMD(dm);
    }

    public List<BtyInventory> selectXM_mx(String xm, String shopName, String startTime, String endTime) {
        return this.btyInventoryMapper.selectXM_mx(xm, shopName, startTime, endTime);
    }

    public List<BtyInventory> selectData(String dm, String startTime, String endTime, String pl) {
        return this.btyInventoryMapper.selectData(dm, startTime, endTime, pl);
    }

    public BtyInventory selectRkAndTotalRkje(BtyInventory btyInventory) {
        return btyInventoryMapper.selectRkAndTotalRkje(btyInventory);
    }

    public List<BtyInventory> selectMoney(BtyInventory btyInventory) {
        return this.btyInventoryMapper.selectMoney(btyInventory);
    }

    public List<String> select_dm() {
        return this.btyInventoryMapper.select_dm();
    }

    public List<String> select_pl(String dm) {
        return this.btyInventoryMapper.select_pl(dm);
    }


    /**
     * 获取前一天的营业数据流水并写入库中
     *
     * @param day 数据的所在日期（天）
     */
    public Integer getDsstorebillAndInsert(String day) {

        String url = "http://btyjt.c3.fxscm.net/cldpoint/getDsstorebill.do?&ent=ENT7617&username=admin&password=admin123&busdate=" + day + "";
        String content = restTemplate.getForObject(url, String.class);
        JSONObject jsonObjectResult = JSON.parseObject(content);
        JSONArray jsonArray = jsonObjectResult.getJSONArray("data");

        List<String> type = Lists.newLinkedList();
        type.add("门店统配入库");
        type.add("门店直配入库");
        type.add("门店自采入库");
        type.add("门店其他入库");
        type.add("门店期初单");
        type.add("店间调入");
        type.add("门店外销退货");
        type.add("门店冲减出库");
        type.add("门店报损出库");
        type.add("门店外销出库");
        type.add("门店统配退货单");
        type.add("门店部门领用");
        type.add("店内档口领用");
        type.add("店间调出");
        type.add("门店其他出库");
        type.add("门店自采退货");
        /**
         * ShopCode    ShopName	ItemSmallClassName  ItemName
         * 没有店名查询的的是所有的店,把获取到的数据取出来便利 然后挨个插入到表中
         */
        JSONObject jsonObject;
        List<BtyInventory> list = Lists.newLinkedList();
        for (int i = 0; i < jsonArray.size(); i++) {
            BtyInventory btyInventory = new BtyInventory();
            //把所有 ItemSmallClassName 为 酱料 的添加到list中
            jsonObject = jsonArray.getJSONObject(i);
            if ("酱料".equals(jsonObject.getOrDefault("ItemSmallClassName", "").toString())
                    && type.contains(jsonObject.getOrDefault("BillType", ""))
                    && !"山西配送中心".equals(jsonObject.getOrDefault("ShopName", "").toString())
                    && !"山东配送中心".equals(jsonObject.getOrDefault("ShopName", "").toString())) {
                //转换时间格式
                String date = convertTime(jsonObject.getOrDefault("MakeTime", "").toString());
                btyInventory.setScrq(date);
                //单据系统编号
                btyInventory.setBillNo(jsonObject.getOrDefault("BillNO", "").toString());

                //入库金额
                btyInventory.setRkje(convertNum(jsonObject.getOrDefault("InStoreMoney", "").toString()));
                btyInventory.setShopCode(jsonObject.getOrDefault("ShopCode", "").toString());
                btyInventory.setShopName(jsonObject.getOrDefault("ShopName", "").toString());
                btyInventory.setPl(jsonObject.getOrDefault("ItemSmallClassName", "").toString());
                //品类code
                btyInventory.setItemTypeCode(jsonObject.getOrDefault("ItemSmallClassCode", "").toString());
                btyInventory.setXm(jsonObject.getOrDefault("ItemName", "").toString());
                //品项code
                btyInventory.setItemCode(jsonObject.getOrDefault("ItemCode", "").toString());
                //判断长度是否大于4
                if (jsonObject.getOrDefault("InBusAmount", "").toString().length() > 4) {
                    //入库数量
                    btyInventory.setRk(convertNum(jsonObject.getOrDefault("InBusAmount", "").toString()));
                } else if (jsonObject.getOrDefault("OutBusAmount", "").toString().length() > 4) {
                    //出库数量
                    btyInventory.setCk(convertNum(jsonObject.getOrDefault("OutBusAmount", "").toString()));
                }
                btyInventory.setRq(convertTime(jsonObject.getOrDefault("busDate", "").toString()));
                //单据类型
                btyInventory.setType(jsonObject.getOrDefault("BillType", "").toString());
                btyInventory.setUnit(jsonObject.getOrDefault("ItemSpec", "").toString());
                //业务单位
                btyInventory.setBusUnit(jsonObject.getOrDefault("BusUnit", "").toString());
                list.add(btyInventory);
            }
        }
        //分批插入数据
        if (list.size() > 0) {
            for (BtyInventory btyInventory : list) {
                try{
                    insertData(btyInventory);
                }catch (Exception e){
                    logger.info("门店库存流水入库数据执行错误，日期：{},data:{}", day,btyInventory.toString());
                }

            }
        }
            logger.info("门店库存流水入库数据：{}条数据", list.size());
            return list.size();

    }


    /**
     * 转换时间格式
     *
     * @param time 参数
     * @return 转换之后的时间格式
     */
    public static String convertTime(String time) {
        // May 31, 2020 1:43:39 PM
        Date date = new Date(time);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        time = simpleDateFormat.format(date);
        return time;
    }

    /**
     * 处理不合理数据，0E-8，0e-8
     */
    private String convertNum(String data) {
        if ("0E-8".equals(data) || "0-8".equals(data) || "0E-12".equals(data) || "0e-12".equals(data)) {
            return "0";
        } else {
            return data;
        }
    }

}